package org.autumn.review.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class DeadLockTest {

    private volatile static int count = 10;
    public static void main(String[] args) {

    }

    private static void livelock() {
        Thread t1 = new Thread(() -> {
            while (count > 0){
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                log.info("count -> {}",count);
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            while (count < 20){
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                log.info("count -> {}",count);
            }
        }, "t2");
        t2.start();
    }

    private static void deadlock() {
        Object a = new Object();
        Object b = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (a){
                try {
                    log.info("lock a");
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b){
                    log.info("lock b");
                }
            }
        }, "t1");
        t1.start();


        Thread t2 = new Thread(() -> {
            synchronized (b){
                try {
                    log.info("lock b");
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a){
                    log.info("lock a");
                }
            }
        }, "t2");
        t2.start();
    }
}
